<template>
  <div class="content">
    <div class="header_box">
      <div class="header_left">私有协议信息</div>
      <div class="header_right">
        <el-form
          :inline="true"
          :model="searFrom"
          class="form_box"
          style="margin-bottom: 20px"
        >
          <el-form-item>
            <el-input
              v-model="searFrom.username"
              placeholder="IP"
              style="width: 200px; margin-right: 10px"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-cascader
              v-model="searFrom.location"
              :options="locationOptions"
              placeholder="请选择国家和地区"
              clearable
              style="width: 200px; margin-right: 10px"
              :props="{ multiple: false, checkStrictly: true }"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="init" style="margin-right: 10px"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="success"
              @click="openAddNodeDialog"
              style="margin-right: 10px"
              >新增节点</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="info"
              @click="navigateToNodeGroupManager"
              style="margin-right: 10px"
              >操作节点组</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="navigateToProtocolPage"
              >操作协议</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="openEmailSettingsDialog"
              >预警邮箱设置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%; border: 1px solid #e0e0e0; border-radius: 5px"
      :header-cell-style="{ background: '#fafbfc', color: '#bbbcc3' }"
      max-height="500"
    >
      <el-table-column type="index" :index="indexMethod" />
      <el-table-column prop="server" label="节点" />
      <el-table-column prop="port" label="端口号" />
      <el-table-column prop="password" label="密码" />
      <el-table-column prop="nodeGroup" label="节点组">
        <template #default="{ row }">
          <el-select
            v-model="row.nodeGroup"
            placeholder="请选择节点组"
            @change="updateNodeGroup(row)"
            style="width: 100%"
          >
            <el-option
              v-for="group in nodeGroups"
              :key="group"
              :label="group"
              :value="group"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="国家和地区">
        <template #default="{ row }">
          <el-cascader
            v-model="row.location"
            :options="locationOptions"
            placeholder="请选择国家和地区"
            style="width: 100%"
            :props="{ multiple: false, checkStrictly: true }"
          />
        </template>
      </el-table-column>
      <el-table-column prop="load" label="负载" />
      <el-table-column prop="domain" label="域名" />
      <el-table-column label="协议" width="200px">
        <template #default="{ row }">
          <el-select
            v-model="row.protocols"
            multiple
            placeholder="请选择协议"
            @change="updateProtocols(row)"
            style="width: 100%"
          >
            <el-option
              v-for="protocol in availableProtocols"
              :key="protocol"
              :label="protocol"
              :value="protocol"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <div class="icon_content">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="编辑"
              placement="top-start"
            >
              <div class="icon_box">
                <el-icon @click="edit(row)" size="20" color="#71778d"
                  ><EditPen
                /></el-icon>
              </div>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="删除"
              placement="top-start"
            >
              <div class="icon_box_d">
                <el-icon @click="remove(row)" size="20" color="#71778d"
                  ><Remove
                /></el-icon>
              </div>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="部署"
              placement="top-start"
            >
              <div class="icon_box">
                <el-icon @click="deploy(row)" size="20" color="#71778d"
                  ><Pointer
                /></el-icon>
              </div>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="解绑"
              placement="top-start"
            >
              <div class="icon_box">
                <el-icon @click="unbind(row)" size="20" color="#71778d"
                  ><Link
                /></el-icon>
              </div>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="page_box">
      <el-pagination
        v-model:current-page="searFrom.pageNo"
        v-model:page-size="searFrom.pageSize"
        :page-sizes="[10, 50, 100, 150]"
        :small="small"
        :disabled="false"
        :background="true"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增节点组弹出窗口 -->
    <el-dialog
      title="新增节点组"
      v-model="addNodeGroupDialogVisible"
      width="30%"
    >
      <el-form>
        <el-form-item label="节点组名称">
          <el-input v-model="newNodeGroupName" placeholder="请输入节点组名称" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="addNodeGroupDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNodeGroup">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增节点弹出窗口 -->
    <el-dialog
      :title="nodeDialogTitle"
      v-model="addNodeDialogVisible"
      width="50%"
    >
      <el-form :model="newNodeData">
        <el-form-item label="节点">
          <el-input
            v-model="newNodeData.fullName"
            placeholder="请输入节点名称"
          />
        </el-form-item>
        <el-form-item label="服务器">
          <el-input v-model="newNodeData.server" placeholder="请输入服务器" />
        </el-form-item>
        <el-form-item label="端口号">
          <el-input v-model="newNodeData.port" placeholder="请输入端口号" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="newNodeData.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="协议">
          <el-select
            v-model="newNodeData.protocols"
            multiple
            placeholder="请选择协议"
          >
            <el-option
              v-for="protocol in availableProtocols"
              :key="protocol"
              :label="protocol"
              :value="protocol"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="newNodeData.remark" placeholder="请输入备注" />
        </el-form-item>
        <!-- 编辑时选择节点组 -->
        <el-form-item v-if="isEditMode" label="节点组">
          <el-select v-model="newNodeData.nodeGroup" placeholder="请选择节点组">
            <el-option
              v-for="group in nodeGroups"
              :key="group"
              :label="group"
              :value="group"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="addNodeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNode">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog title="预警邮箱设置" v-model="emailDialogVisible" width="30%">
      <el-form>
        <el-form-item label="邮箱地址">
          <el-input
            v-model="newEmailAddress"
            placeholder="请输入邮箱地址"
            @keyup.enter="addEmailAddress"
            style="margin-bottom: 10px"
          />
          <el-button type="primary" @click="addEmailAddress">添加</el-button>
        </el-form-item>
        <el-form-item>
          <div
            v-for="(email, index) in emailAddresses"
            :key="index"
            style="margin-bottom: 5px; margin-left: 10px"
          >
            {{ email }}
            <el-button type="text" @click="removeEmailAddress(index)"
              >删除</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="emailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEmailSettings">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { defineOptions, ref, onBeforeMount, computed } from "vue";
import * as userApi from "../../../api/project3/user/user.js";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
defineOptions({ name: "UserList" });
const emailDialogVisible = ref(false);
const emailAddresses = ref([]);
const newEmailAddress = ref("");

// 示例数据
let tableData = ref([
  {
    fullName: "节点1",
    server: "192.168.1.1",
    port: "8080",
    password: "password1",
    protocols: ["协议1", "协议2"],
    nodeGroup: "组1",
    location: ["中国", "华东"],
    load: "50%",
    domain: "baidu.com",
  },
  {
    fullName: "节点2",
    server: "192.168.1.2",
    port: "8081",
    password: "password2",
    protocols: ["协议2"],
    nodeGroup: "组2",
    location: ["美国", "西部"],
    load: "30%",
    domain: "baidu.com",
  },
]);

// 搜索表单数据
let searFrom = ref({
  username: "",
  pageNo: 1,
  pageSize: 10,
  location: [], // 新增的国家和地区字段
});

let total = ref(0);

const router = new useRouter();

// 假设从后端获取的协议列表
const availableProtocols = ref(["协议1", "协议2", "协议3"]);

const addNodeGroupDialogVisible = ref(false);
const newNodeGroupName = ref("");

const addNodeDialogVisible = ref(false);
const newNodeData = ref({
  fullName: "",
  server: "",
  port: "",
  password: "",
  protocols: [],
  nodeGroup: "",
  remark: "",
});
const isEditMode = ref(false);
const nodeGroups = ref(["组1", "组2", "组3"]); // 假设的节点组列表

const nodeDialogTitle = computed(() =>
  isEditMode.value ? "编辑节点" : "新增节点"
);

// 国家和地区选项
const locationOptions = ref([
  {
    value: "中国",
    label: "中国",
    children: [
      { value: "华东", label: "华东" },
      { value: "华南", label: "华南" },
      { value: "华北", label: "华北" },
      { value: "西部", label: "西部" },
      { value: "东北", label: "东北" },
    ],
  },
  {
    value: "美国",
    label: "美国",
    children: [
      { value: "东部", label: "东部" },
      { value: "西部", label: "西部" },
      { value: "南部", label: "南部" },
      { value: "北部", label: "北部" },
    ],
  },
  // 其他国家和地区...
]);

const init = async () => {
  const res = await userApi.page(searFrom.value);
  const { records } = res;
  tableData.value = records;
  total.value = res.total;
};

// 显示新增节点组对话框
const toInfo = () => {
  addNodeGroupDialogVisible.value = true;
};

// 导航到协议页面
const navigateToProtocolPage = () => {
  console.log("Navigating to protocol page");
  router.push({ name: "project3_private_ProtocolPage" });
};

const saveNodeGroup = () => {
  // 在这里添加保存节点组的逻辑
  console.log("保存节点组:", newNodeGroupName.value);
  addNodeGroupDialogVisible.value = false;
};

const openAddNodeDialog = () => {
  isEditMode.value = false;
  newNodeData.value = {
    fullName: "",
    server: "",
    port: "",
    password: "",
    protocols: [],
    nodeGroup: "",
    remark: "",
  };
  addNodeDialogVisible.value = true;
};

const saveNode = () => {
  if (isEditMode.value) {
    // 编辑节点逻辑
    console.log("编辑节点:", newNodeData.value);
  } else {
    // 新增节点逻辑
    console.log("新增节点:", newNodeData.value);
  }
  addNodeDialogVisible.value = false;
};

const edit = (row) => {
  isEditMode.value = true;
  newNodeData.value = {
    fullName: row.fullName || "",
    server: row.server || "",
    port: row.port || "",
    password: row.password || "",
    protocols: row.protocols || [],
    nodeGroup: row.nodeGroup || "",
    remark: row.remark || "",
  };
  addNodeDialogVisible.value = true;
};

const remove = (row) => {
  // 在这里添加删除节点的逻辑
  console.log("删除节点:", row);
};

const handleSizeChange = (newSize) => {
  searFrom.value.pageSize = newSize;
  init();
};

const handleCurrentChange = (newPage) => {
  searFrom.value.pageNo = newPage;
  init();
};

const navigateToNodeGroupManager = () => {
  router.push({ name: "NodeGroupManager" });
};

const updateNodeGroup = (row) => {
  // 在这里添加更新节点组的逻辑
  console.log("更新节点组:", row.nodeGroup);
};

const deploy = (row) => {
  // 在这里添加部署节点的逻辑
  console.log("部署节点:", row);
};

const unbind = (row) => {
  // 在这里添加解绑节点的逻辑
  console.log("解绑节点:", row);
};

const updateProtocols = (row) => {
  // 在这里添加更新协议的逻辑
  console.log("更新协议:", row.protocols);
};

onBeforeMount(() => {
  //  init()
});
const openEmailSettingsDialog = () => {
  emailDialogVisible.value = true;
};
const saveEmailSettings = () => {
  // 保存邮箱设置逻辑
  console.log("保存邮箱地址:", emailAddresses.value);
  emailDialogVisible.value = false;
};
const addEmailAddress = () => {
  if (
    newEmailAddress.value &&
    !emailAddresses.value.includes(newEmailAddress.value)
  ) {
    emailAddresses.value.push(newEmailAddress.value);
    newEmailAddress.value = "";
  } else {
    ElMessage.warning("邮箱地址不能为空或已存在");
  }
};
const removeEmailAddress = (index) => {
  emailAddresses.value.splice(index, 1);
};
</script>
<style lang="less" scoped>
.header_left {
  border-radius: 15px 0px 0px 0px;
  font-weight: 800;
}
.header_right {
  background-color: #ffffff;
  justify-content: flex-end;
  border-radius: 0px 15px 0px 0px;
}
:deep(.form_box) {
  width: 80%;
  height: 40%;
  margin: 0px;
  display: flex;
  justify-content: flex-end;
}
.operation-buttons {
  margin: 20px 0;
}
</style>